//基础类
var EAS_JS = {
	//版本号属性
	version : "4.0.1",
	
	//环境初始化方法
	init : function () {
		//环境初始化
		$(document).ready(function () {
			var privateTag = [];
			
			privateTag.push("<div id='_Ajax_tip' style='display:none;" + EAS_JS.Setting.style.ajaxLoading + "'></div>");
			privateTag.push("<div id='_Dialog_tmp' style='display:none;'></div>");
			privateTag.push("<div id='_Dialog_bg' style='display:none;" + EAS_JS.Setting.style.dialogBackground + "'></div>");
			privateTag.push("<div id='_Dialog' style='display:none;" + EAS_JS.Setting.style.dialog + "'>");
			privateTag.push("<div id='_Dialog_title' style='" + EAS_JS.Setting.style.dialogTitle + "'></div>");
			privateTag.push("<div id='_Dialog_content' style=''></div>");
			privateTag.push("<div id='_Dialog_button' style='float:right;'><input type='button' id='_dialog_btn_ok' value='" + EAS_JS.Setting.txt.dlgBtnSubmit + "' style='" + EAS_JS.Setting.style.dialogButton + "' /><input type='button' id='_dialog_btn_cancel' value='" + EAS_JS.Setting.txt.dlgBtnCancel + "' style='" + EAS_JS.Setting.style.dialogButton + "'/></div>");
			privateTag.push("</div>");
			$('body').append(privateTag.join(""));

			delete privateTag;

			//Ajax的事件提示
			$('#_Ajax_tip')
				.ajaxSend (function (evt, req, settings) {
					$("#_Ajax_tip")
						.css({top : $(document).height() - 40 + "px"})
						.html(EAS_JS.Setting.txt.ajaxLoading)
						.show();
					
					EAS_JS.Debug.httpLog.push({request : settings.url});
					EAS_JS.Data.ajaxLoadError = false;
				})
				.ajaxSuccess (function (evt, request, settings) {
					$("#_Ajax_tip").html(EAS_JS.Setting.txt.ajaxSuccess);
				})	
				.ajaxError (function (evt, request, settings) {
					$("#_Ajax_tip").html(EAS_JS.Setting.txt.ajaxError);
					EAS_JS.Data.ajaxLoadError = true;
				})
				.ajaxComplete (function (evt, request, settings) {
					if (!EAS_JS.Data.ajaxLoadError)
					{
						$("#_Ajax_tip").hide();
						EAS_JS.Debug.httpLog[EAS_JS.Debug.httpLog.length - 1].response = request.responseText ? request.responseText : request.responseXML;
					}
				})
				;
		});
	}
};

//Debug类
EAS_JS.Debug = {
	isDebug : false,
	httpLog : []
};

//配置类
EAS_JS.Setting = {
	txt : {
		ajaxLoading : "正在加载。。。",
		ajaxError : "加载数据时发生错误，请重试。",
		ajaxSuccess : "请求成功，正在解析。",
		emptyTable : "暂无数据",
		dlgBtnSubmit : '确定',
		dlgBtnCancel : '取消',
	},
	style : {
		emptyTable : "",
		advTable : {
			"single" : "#A9D5F4",
			"dual" : "#FFF",
			"over" : "#EFEFEF"
		},
		ajaxLoading : "left:10px;position:absolute;background:#FFF1A8;color:#000;z-index:99;padding:5px 10px;",
		dialogBackground : "z-index:98;filter:alpha(opacity=50);opacity:0.5;top:0;left:0;width:100%;height:100%;position:absolute;background:#000;",
		dialog : "border:5px #f5f5f5 solid;background:#fff;z-index:99;position:absolute;",
		dialogTitle : "background:#99BBE8;font-size:14px;padding-left:5px;line-height:200%;color:#FFF;",
		dialogButton : "color:#0066CC;background:#FFF;border:1px #CCC solid;margin:5px;padding:5px 10px;"
	}
};

EAS_JS.Data = {};

//脚本类
EAS_JS.Script = {
	_queue : [],
	_modules : [],
	_loadLock : 0,

	/*
	动态异步加载脚本方法
	
	只有在window.onload之前调用，能保证加载顺序。如要在window.onload之后保证加载顺序，请使用 build+run 方法

	@param json {url : , load : }
	*/
	load : function (pars) {
		if ( ($.browser.msie || $.browser.safari) && !$.isReady)
		{
			this._IEandCHRload(pars);
		}
		else{
			this._FFandOPload(pars);
		}

		return this;
	},

	_FFandOPload : function (pars) {
		var script = document.createElement("script");
		script.setAttribute("src", pars.url);

		if (pars.load)
		{
			script.done = false;
			script.onload = script.onreadystatechange = function() {
				if ( !script.done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
					script.done = true;
					pars.load();
				}
			}
		}

		document.body.appendChild(script);
	},

	_IEandCHRload : function (pars) {
		document.write(unescape("%3Cscript src='" + pars.url + "' type='text/javascript'%3E%3C/script%3E"));
		
		if (pars.load)
		{
			$(document).ready(pars.load);
		}
	},

	//构造模块树
	build : function (pars) {
		this._modules[pars.name] = pars;

		return this;
	},

	/*
	运行模块
	生成加载队列，然后交由 _Execute 方法处理
	*/
	run : function (pars) {
		var _module = this._modules[pars.name];

		if (_module.requires)
		{
			//是否依赖其他模块
			this._loadLock++;
			for (var i = 0, j = _module.requires.length;i < j ;i++ )
			{
				this.run({name : _module.requires[i]});
			}
			this._loadLock--;
		}

		//依赖外部脚本
		if (_module.url)
		{
			this._queue.push({url :  _module.url});
		}
		//依赖自定义脚本
		if (_module.def)
		{
			this._queue.push({def :  _module.def});
		}

		if (!this._loadLock)
		{
			this._Execute();
		}
	},

	_Execute : function () {
		while (this._queue.length > 0)
		{
			if (this._queue[0].url)
			{
				//如果下一步也为外部脚本，并且在window.onload之前，使用同步加载
				if ( this._queue[1].url && (!$.isReady || $.browser.opera || $.browser.mozilla) )
				{
					this.load({
						url : this._queue[0].url
					});
				}
				//否则使用逐步加载
				else{
					this.load({
						url : this._queue[0].url,
						load : function () {EAS_JS.Script._queue.shift();EAS_JS.Script._Execute();}
					});

					break;
				}
			}
			else{
				this._queue[0].def();
			}

			this._queue.shift();
		}
	}
};

//Ajax类
EAS_JS.Ajax = {
	otherCallback : null,

	//加载html到页面
	getHTML : function (url, target) {
		$("#"+target).load(url);
	},

	//加载json
	getJSON : function (pars) {
		var data	 = pars.data ? pars.data : {},
			callback = pars.callback ? pars.callback : this.executeJSON,
			format	 = pars.format ? pars.format : 'json';

		$.post(pars.url, data, callback, format);
	},

	executeJSON : function (json) {
		if (typeof(json.form) != "undefined")
		{
			EAS_JS.Form.setElements(json.form);
		}

		if (typeof(json.list) != "undefined"){
			EAS_JS.Table.makeTable(json.list);
		}

		if (typeof(json.elements) != "undefined"){
			EAS_JS.Ajax.setElements(json.elements);
		}

		if (EAS_JS.Ajax.otherCallback != null)
		{
			var t = EAS_JS.Ajax.otherCallback;
			EAS_JS.Ajax.otherCallback = null;

			t(json);
		}
	},

	setElements : function (elements) {
		for (elementID in elements) {
			var elementValue = elements[elementID];

			if($("#" + elementID).length && elementValue.toString() != "") {
				$("#" + elementID).html(elementValue);
			}
		}
	}
};

//表格类(DataGrid)
EAS_JS.Table = {
	templateID :  "tempArea",
	targetID : "targetDiv",
	pageTargetID : "pageDiv",
	url : "",
	dateVal : "",

	rowSetF : null,
	
	pageSize: 15,

	total : 0,
	nowPage : 1,

	objectCache : {
		"target" : null,
		"pageTarget" : null,
		"list" : null
	},
	
	isCache : true,
	listMode : 0,		//列表模式，0=普通，1=高级（支持排序及行渐变色）

	templateCache : [],
	cacheID : 0,

	otherCallback : null,

	start : function () {
		if (arguments.length > 0){
			//渲染设定
			var opts = arguments[0];
			
			for (option in opts) {
				this[option] = opts[option];
			}
		}
		
		//发起请求
		EAS_JS.Ajax.getJSON({
			url : this.url,
			data : this.dateVal + "&page=" + this.nowPage + "&pageSize=" + this.pageSize
		});
	},

	makeTable : function (list) {
		if (!$("#" + this.targetID).length || !list.item)
		{
			//是否指定内容区
			return false;
		}

		this.total = list.total ? list.total: 0;
		var rowCount = list.item.length;
		
		if (rowCount > 0)
		{
			this.objectCache.pageTarget = $("#" + this.pageTargetID);
			this.objectCache.target = $("#" + this.targetID);
			this.objectCache.list = list;

			if (this.listMode)
			{
				this._adList();
			}
			else{
				this._baseList();
			}
			
			if (this.objectCache.pageTarget) {
				if(this.total > 0) {
					this.objectCache.pageTarget.html(this.pageNav());
					
					$("#" + this.pageTargetID).show();
				}
			}

			this.objectCache.target = this.objectCache.pageTarget = this.objectCache.list = null;
		}
		else{
			$("#" + this.targetID).html("<div class='" + EAS_JS.Setting.style.emptyTable + "'>" + EAS_JS.Setting.txt.emptyTable + "</div>");
			
			$("#" + this.pageTargetID).hide();
		}

		if (this.otherCallback != null)
		{
			var t = this.otherCallback;
			this.otherCallback = null;

			t();
		}

		if($.browser.msie) {
			CollectGarbage();
		}
	},

	loadTemplate : function () {
		var t = "";

		if (this.isCache)
		{
			//判断是否打开cache模式
			for (var ii = this.templateCache.length - 1;ii >=0 ;ii-- )
			{
				if (this.templateID == this.templateCache[ii].templateID)
				{
					t = this.templateCache[ii].templateContent;
					break;
				}
			}
		}

		if (t == "")
		{
			t = unescape($("#" + this.templateID).html());
			t = t.replace(/\/\/\//g, "//");
			t = t.replace(/hs_src/g, "src");
			t = t.replace(/hs_href/g, "href");

			this.templateCache[this.cacheID] = {"templateID" : this.templateID, "templateContent" : t};
			this.cacheID = (this.cacheID + 1) > 10 ? 0 : this.cacheID + 1;
		}

		return t;
	},

	setURL : function (sURL){
		this.nowPage = 1;
		this.url = sURL;
	},

	_templateEvaluate : function (rowData, template) {
		var t = template;
		
		for (id in rowData) {
			var elementValue = rowData[id];
			
			while (t.indexOf("#{" + id + "}") != -1)
			{
				t = t.replace("#{" + id + "}", elementValue);
			}
		}
		
		return t;
	},

	_baseList : function () {
		var rowContent	= [];
		var rowCount	= this.objectCache.list.item.length;
		var t			= this.loadTemplate();

		for (var i = 0; i < rowCount; i++) {
			var p = this.rowSetF(this.objectCache.list.item[i]);

			rowContent.push(this._templateEvaluate(p, t));
		}
		
		this.objectCache.target.html(rowContent.join(""));
	},
	
	_adList : function () {
		var rowContent	= [];
		var rowCount	= this.objectCache.list.item.length;
		var template	= this.loadTemplate();

		this.dataArray = this.dataCache == this.objectCache.list ? this.dataArray : [];
		this.dataSort = this.dataCache == this.objectCache.list ? this.dataSort : new Array(rowCount);
		this.dataCache = this.objectCache.list;
		
		for (var i = 0; i < rowCount; i++) {
			if (this.dataSort[i])
			{
				//排序后的输出
				var t = this.dataCache.item[this.dataSort[i][1]];	
			}
			else{
				//第一次列表，填充字段数组
				//dataArray[0] 为第一列的所有行
				var columnIndex = 0;
				var t = this.dataCache.item[i];

				for (elementID in t) {
					if (!this.dataArray[columnIndex])
					{
						this.dataArray[columnIndex] = [];
					}
					this.dataArray[columnIndex].push([t[elementID], i]);
					columnIndex++;
				}
			}
			t.rowIndex = i;
			
			var p = this.rowSetF(t);

			this.objectCache.target.html(this._templateEvaluate(p, template));

			if ($("#Row_" + i))
			{
				if (i % 2)
				{
					$("#Row_" + i).css({background : EAS_JS.Setting.style.advTable.single});
				}
				else{
					$("#Row_" + i).css({background : EAS_JS.Setting.style.advTable.dual});
				}
				
				$("#Row_" + i).bind("mouseover", function () {
					var t = this.style.background;
					this.style.background = EAS_JS.Setting.style.advTable.over;
					eval('$("#' +  this.id + '").bind("mouseout", function () {this.style.background = "' + t + '";});');
				});
			}
		}

		this.dataSort = null;
	},

	sort: function (columnIndex) {
		if (!this.dataArray){
			return false;
		}
		
		var dataA = this.dataArray[columnIndex];
		var aLength = dataA.length;
		var maxValue = null;
		var op = arguments[1] ? arguments[1] : true;
		this.dataSort = null;

		for (var i = 0;i < aLength - 1 ;i++ )
		{
			maxValue = dataA[i];
			for (var j = aLength - 1;j >= i ;j-- )
			{
				if ((dataA[j][0] < maxValue[0]) == op)
				{
					dataA[i] = dataA[j];
					dataA[j] = maxValue;
					maxValue = dataA[i];
				}
			}
		}

		this.dataSort = dataA;
		this.makeTable(this.dataCache);
	},

	pageNav : function () {
		var total = this.total;
		var nowPage	= this.nowPage ? parseInt(this.nowPage) : 1;
		var pageSize= this.pageSize ? this.pageSize : 10;
		var pageCount = total/pageSize;
		pageCount = pageCount > parseInt(pageCount) ? parseInt(pageCount) + 1 : parseInt(pageCount);

		if (nowPage-4 < 1){
			var RootPage = 1;
		}
		else{
			var RootPage = nowPage-4;
		}
		if (nowPage+4 > pageCount){
			var EndPage = pageCount;
		}
		else{
			var EndPage = nowPage+4;
		}
		
		var pageContent = "<div class='EAS_Table-pageNav'>";
		if (!this.listMode)
		{
			pageContent += "<span class='total'>共&nbsp;"+total+"&nbsp;条记录&nbsp;"+nowPage+"/"+pageCount+"页</span>&nbsp;";
		}

		if (nowPage > 1){
			pageContent += '<a href="javascript:;" onclick="javascript: EAS_JS.Table.pageGo(1);" title="首页" class="first">首页</a>&nbsp;';
			pageContent += '<a href="javascript:;" onclick="javascript: EAS_JS.Table.pageGo(' + (nowPage - 1) + ');" title="上一页" class="list">上一页</a>&nbsp;';
		}

		for (var i=RootPage;i<=EndPage;i++){
			if (i==nowPage){
				pageContent += '<span class="current">' + i + '</span>&nbsp;';
			}
			else{
				pageContent += '<a href="javascript:;" onclick="javascript: EAS_JS.Table.pageGo(' + i + ');" class="list">' + i + '</a>&nbsp;';
			}
		}

		if (nowPage < pageCount){
			pageContent += '<a href="javascript:;" onclick="javascript: EAS_JS.Table.pageGo(' + (nowPage + 1) + ');" title="下一页" class="list">下一页</a>&nbsp;';
			pageContent += '<a href="javascript:;" onclick="javascript: EAS_JS.Table.pageGo(' + pageCount + ');" title="尾页" class=\"last\">尾页</a>&nbsp;';
		}
		
		pageContent += "</div>";

		return pageContent;
	},

	pageGo : function (nowPage) {
		EAS_JS.Table.nowPage = nowPage;
		EAS_JS.Table.start();
	}
};

EAS_JS.Form = {
	formID : "form1",

	url : "",
	dateVal : "",

	start : function () {
		$("#" + this.formID)[0].reset();

		EAS_JS.Ajax.getJSON({
			url : this.url,
			data : this.dateVal
		});
	},
	
	setElements : function (valueBox) {
		if (!$("#" + this.formID))
		{
			return false;
		}

		var elements = $("#" + this.formID).find(":input");
		var elementsCount = elements.length;
		var rndCode = Math.random() * 10000000000000000;

		for (var i = 0; i < elementsCount;i++) {
			var element = elements[i];
			var eName = element.name;
			if (!element.id) {
				element.id = "__form" + rndCode + "_"+ i;
			}

			if (typeof(valueBox[eName]) != "undefined"){
				var value = valueBox[eName];

				switch (element.type.toLowerCase()) {
    				case "radio" :
    					if (element.value == value) {
    						element.setAttribute("checked", "checked");
    					}
						else {
    					    element.removeAttribute("checked");
    					}
    					
    					break;
    				case "checkbox" :
    					element.checked = false;
    					
    				    valueT = "," + value + ",";
    				    if (valueT.indexOf("," + element.value + ",") != -1){
    				    	element.checked = true;
    				    }
    				    
    					break;
    				case "select-one" : 
						value = value.toString();
    				    if(value.toLowerCase().indexOf("(build-select)") != -1){
    				    	$("#" + element.id).empty();

        				    var items=[];
							items=value.split(";");
							
							var current=items[0].split(",");
							if(current[1]!=null && current[1]!=""){
								current=current[1];
							}
							else{
								current=-1;
							}
							
							for(var ii=1;ii<items.length;ii++){
								var a=items[ii].split(",");
								if(a[0]!=null && a[0]!="" && a[1]!=null && a[1]!=""){
									var newOpt=new Option(a[0],a[1]);
									
									element.options[element.options.length]=newOpt;
									element.options[element.options.length-1].selected=(a[1]==current)?true:false;
								}
							}
						}
						else {
        				    for(var is=0; is<element.options.length; is++) {
        				        opt = element.options[is];
        				        evalue = opt.value;

        				        if(evalue == value) {
        				            opt.selected=true;
        				        }
								else {
        				            opt.selected=false;
        				        }
        				    }
    				    }
    				    
        				break;
    				case "select-multiple" :
    				    valueArray = value.split(";");

						$("#" + element.id).empty();

    					for(var ii=0;ii<valueArray.length;ii++){
							var a=valueArray[ii].split(",");
							
							if(a[0]!=null && a[0]!="" && a[1]!=null && a[1]!=""){
								var newOpt=new Option(a[0],a[1]);
								
								element.options[element.options.length]=newOpt;
								element.options[element.options.length-1].selected=(a[2]=="true")?true:false;
							}
						}
    					break;
    				case "textarea" :
					case "text" :
						value = value.replace(/&quot;/g, '"');
						value = value.replace(/&#039;/g, "'");
						value = value.replace(/&#92;/g, "\\");
						value = value.replace(/&lt;/g, "<");
						value = value.replace(/&gt;/g, ">");
						value = value.replace(/&#123;/g, "{");
						value = value.replace(/&#125;/g, "}");
						element.value = value;
    					break;
					case "hidden" :
    				default : 
    					element.setAttribute("value",value);
    					break;
				}
			}
		}
	}
};

EAS_JS.Dialog = {
	isLoaded : false,
	hideElement : [],
	resize : {
		top : null,
		left : null,
		width : 0,
		height : 0
	},
	
	/*
	打开一个对话框
	op = {
		source : string/object,
		model : true/false,
		title : string,
		button : {ok,cancel}
	}
	*/
	open : function (op) {
		if (EAS_JS.Dialog.isLoaded)
		{
			return false;
		}
		else{
			EAS_JS.Dialog.isLoaded = true;
		}

		$("#_Ajax_tip").show();

		if (op.model)
		{
			//是否模式对话框
			$("#_Dialog_bg")
				.css({
					width : $(document).width() + "px",
					height : $(document).height() + "px"
				})
				.show();

			//隐藏select控件，for ie6
			var nodes = $("select:not(#_Dialog select)");
			for (var i = 0;i < nodes.length ;i++ )
			{
				var hideName = nodes[i].id ? "#" + nodes[i].id : "select[name='" + nodes[i].name + "']";
				
				if (nodes[i].style.display != "none" && hideName.length > 0)
				{
					EAS_JS.Dialog.hideElement.push(hideName);
				}
			}
			$(EAS_JS.Dialog.hideElement.join(",")).hide();
			nodes = null;
		}

		if (op.title)
		{
			//是否显示标题栏
			$('#_Dialog_title')
				.html(op.title)
				.show();
		}
		else{
			$('#_Dialog_title').hide();
		}

		if (op.button)
		{
			//是否显示按钮栏
			$('#_Dialog_button').show();

			if (op.button.ok)
			{
				//捆绑按钮自定义事件
				$('#_dialog_btn_ok').click(op.button.ok);
			}

			//捆绑按钮默认事件
			$('#_dialog_btn_ok')
				.click(EAS_JS.Dialog.close)
				.show();

			if (op.button.cancel)
			{
				$('#_dialog_btn_cancel')
					.show()
					.click(op.button.cancel)
					.click(EAS_JS.Dialog.close);
			}
			else{
				$('#_dialog_btn_cancel').hide();
			}
		}
		else{
			$('#_Dialog_button').hide();
		}
		
		if (typeof(op.source) == 'string')
		{
			//使用远程文件
			$("#_Dialog_tmp").load(op.source, "", EAS_JS.Dialog._show);
		}
		else{
			//使用页面隐藏元素内容
			$('#_Dialog_tmp').html(op.source.html());
			EAS_JS.Dialog._show();
		}
	},
	
	close : function () {
		$("#_Dialog,#_Dialog_bg").hide();

		EAS_JS.Dialog.isLoaded = false;
	
		//恢复select控件原状
		if (EAS_JS.Dialog.hideElement.length)
		{
			$(EAS_JS.Dialog.hideElement.join(",")).show();
			EAS_JS.Dialog.hideElement = [];
		}

		//清理自定义事件
		$('#_dialog_btn_ok,#_dialog_btn_cancel').unbind();
	},

	_resize : function () {
		var scrollLeft = $(document).scrollLeft(),
			scrollTop = $(document).scrollTop(),
			width = $(document).width();

		$("#_Dialog").css({
			left : (width - $("#_Dialog").outerWidth(true)) / 2 - scrollLeft + "px",
			top : 100 + scrollTop + "px"
		});
	},
	
	_show : function () {
		$("#_Ajax_tip").show();

		var sHTML = $("#_Dialog_tmp").html();

		$("#_Dialog_tmp").empty();
		$("#_Dialog_content").html(sHTML);
		sHTML = null;

		EAS_JS.Dialog._resize();

		$("#_Dialog").show(1000, function () {$("#_Ajax_tip").hide();});

		$(window)
			.bind('resize', EAS_JS.Dialog._resize)
			.bind('scroll', EAS_JS.Dialog._resize);
	}
};

EAS_JS.init();